<script lang="ts" setup>
import { h, onMounted, ref } from 'vue';
import { Input, Modal, message } from 'ant-design-vue';
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined, ExportOutlined, FolderOpenOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { useRouter } from 'vue-router';
import useClipboard from 'vue-clipboard3';
import EditCourseModal from './EditCourse.vue';
import { createCoursesApi, deleteCoursesApi, fetchCoursesApi } from '@/api/Teacher/courseApi';

// 模态框状态
const isModalVisible = ref(false);
const isVisible = ref(false);

interface CourseFile {
  courseFileId: string;
  name: string;
  parentId: string | null;
  filePath: string;
  createdAt: string;
  childId: string;
  tag: string;
  level: number;
  courseId: string;
  sortOrder: number | null;
  courseImageUrl: string;
  childFiles: any[];
  sourceFiles: any[];
  webSourses: any[];
}

const { toClipboard } = useClipboard();
const loading = ref(false);
const courseImage = ref<any>([]);
const teachers = ref([{ name: '', institution: '', position: '', title: '', imageFile: null, imagePreview: '' }]);
const courseData = ref<any>([]);
const searchValue = ref('');
const router = useRouter();
const courseId = ref('');
const courseName = ref('');
const courseTags = ref('');
const courseDescription = ref('');
const deleteConfirmVisible = ref(false);

const fetchCourses = async (searchValue: string) => {
  try {
    loading.value = true;
    const response = await fetchCoursesApi(searchValue);
    courseData.value = response.data;
  }
  catch (error) {
    message.error('获取课程列表失败');
    console.error(error);
  }
  finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchCourses('');
});

const handleSearch = (value: string) => {
  searchValue.value = value;
  fetchCourses(value);
};

const handleItemClick = (item: any) => {
  const path = `${item.courseFileId}|`;
  router.push({
    path: `/teacher/manage/chapter/${path}`,
    replace: true, // 强制导航
  });
};

// 控制模态框的打开与关闭
const handleCancel = () => {
  isModalVisible.value = false;
  courseImage.value = [];
  teachers.value = [{ name: '', institution: '', position: '', title: '', imageFile: null, imagePreview: '' }];
};

// 表单重置
const resetForm = () => {
  courseName.value = '';
  courseTags.value = '';
  courseDescription.value = '';
  courseImage.value = [];
  teachers.value = [{ name: '', institution: '', position: '', title: '', imageFile: null, imagePreview: '' }];
};

// 提交数据
const handleOk = async () => {
  isModalVisible.value = false;

  try {
    const courseFormData = new FormData();

    // 上传课程图片
    if (courseImage.value.length > 0)
      courseFormData.append('files', courseImage.value[0].originFileObj);

    // 过滤出已填写的教师信息
    const filteredTeachers = teachers.value.filter(
      teacher => teacher.name && teacher.institution && teacher.position && teacher.title,
    );

    // 构造教师列表
    const teacherList = filteredTeachers.map((teacher, index) => {
      if (teacher.imageFile)
        courseFormData.append('files', teacher.imageFile as File);

      return {
        id: index + 1,
        teacherName: teacher.name,
        teacherSchool: teacher.institution,
        teacherJob: teacher.position,
        teacherTitle: teacher.title,
      };
    });

    // 构造课程数据
    const payload = {
      courseName: courseName.value,
      courseTag: courseTags.value,
      teacher: teacherList,
      courseDescription: courseDescription.value,
    };

    courseFormData.append('course', JSON.stringify(payload));

    // 发送请求到后端
    await createCoursesApi(courseFormData)
    // 处理响应
    message.success('课程创建成功');
    resetForm();
    await fetchCourses(searchValue.value);
  }
  catch (error) {
    message.error('创建课程请求失败');
  }
};

// 课程图片上传处理
const handleCourseImageChange = ({ fileList }: any) => {
  courseImage.value = fileList;
};

// 教师图片上传处理
const handleTeacherImageChange = (index: number, { fileList }: any) => {
  const file = fileList[0];
  if (file) {
    const objectURL = URL.createObjectURL(file.originFileObj); // 创建对象URL
    teachers.value[index].imageFile = file.originFileObj; // 保存文件对象
    teachers.value[index].imagePreview = objectURL; // 将预览 URL 存储为响应式属性
  }
  else {
    // 如果 fileList 为空，则清除图像文件和预览
    teachers.value[index].imageFile = null;
    teachers.value[index].imagePreview = '';
  }
};

// 方法：添加教师
const handleAddTeacher = () => {
  teachers.value.push({ name: '', institution: '', position: '', title: '', imageFile: null, imagePreview: '' });
};

// 方法：更新教师信息
const handleTeacherChange = (index: number, field: string, value: string | File) => {
  const newTeachers = [...teachers.value];
  newTeachers[index] = { ...newTeachers[index], [field]: value };
  teachers.value = newTeachers;
};

// 方法：删除教师
const handleRemoveTeacher = (index: number) => {
  teachers.value.splice(index, 1);
};
// 分享复制链接
const copyUrl = async (item: any) => {
  const sourceIdAsBigInt = BigInt(item.courseId);
  const incrementedSourceId = sourceIdAsBigInt + BigInt(1); // 加 1
  const folderId = incrementedSourceId.toString();
  const shareUrl = import.meta.env.VITE_LOCAL_IP
  const urlToCopy = `http://${shareUrl}/user/learningNew/course/${item.courseId}/${folderId}`;

  try {
    // 使用 vue-clipboard3 的剪贴板功能复制 URL
    await toClipboard(urlToCopy);
    message.success('URL 已复制到剪贴板');
  }
  catch (error) {
    // 如果剪贴板复制失败，弹出模态框，供用户手动复制
    message.error('复制失败，请手动复制');

    Modal.info({
      title: '分享课程',
      content: () => h('div', { style: { marginLeft: '-20px' } }, [
        h('p', { style: { fontSize: '16px', marginBottom: '10px', color: '#333' } }, '这是课程链接'),
        h(Input.TextArea, {
          value: urlToCopy,
          readonly: true,
          style: {
            width: '100%',
            height: '100px',
            padding: '10px',
            fontSize: '16px',
            border: '1px solid #d9d9d9',
            borderRadius: '4px',
            backgroundColor: '#f5f5f5',
            color: '#333',
            resize: 'none',
          },
        }),
      ]),
      okText: '关闭',
      onOk() {
      },
    });
  }
};
// 方法：处理编辑事件
const handleMove = (item: any) => {
  courseId.value = item.courseId;
  isVisible.value = true; // 显示模态框
};
// 方法：关闭模态框
const handleNotMove = () => {
  isVisible.value = false; // 隐藏模态框
}

const setDeleteConfirmVisible = (visible: boolean) => {
  deleteConfirmVisible.value = visible;
};
const deleteItemTmp = ref<any>(null);

// 删除请求的发出
const handleDelete = async (item: any) => {
  try {
    setDeleteConfirmVisible(false)
    // 调用接口，删除课程文件
    await deleteCoursesApi(item.courseId, item.courseFileId);
    // 检查返回结果并显示相应提示
    message.success('课程文件删除成功');
    await fetchCourses(searchValue.value); // 重新获取课程列表
  }
  catch (error) {
    // 捕获异常并输出错误信息
    console.error('删除课程文件时出错:', error);
    message.error('请求失败');
  }
};

// 确认删除对话框的函数
const showDeleteConfirm = (item: any) => {
  deleteItemTmp.value = item;
  setDeleteConfirmVisible(true);
  // Modal.confirm({
  //   title: '删除',
  //   icon: h(ExclamationCircleOutlined), // 正确导入图标
  //   content: h('span', { style: { fontSize: '16px' } }, '您确定要删除所选中的内容吗？内容一旦被删除将不能恢复。'),
  //   okText: '确定',
  //   okType: 'danger',
  //   centered: true,
  //   width: 550,
  //   closable: true,
  //   cancelButtonProps: { style: { display: 'none' } }, // 隐藏取消按钮
  //   onOk() {
  //     handleDelete(item); // 调用删除函数并传入 item
  //   },
  //   onCancel() {
  //     console.log('取消操作');
  //   },
  //   okButtonProps: {
  //     style: {
  //       backgroundColor: '#FF7575',
  //       borderColor: '#FF7575',
  //       fontSize: '16px',
  //       color: '#FFFFFF',
  //       borderRadius: '0px',
  //       padding: '10px 20px',
  //     },
  //   },
  // });
};
</script>

<template>
  <div class="courseManager">
    <a-spin :spinning="loading" size="large">
      <div class="header-section">
        <div class="controlc">
          <h2 class="title">
            我的课程
          </h2>
          <a-space class="actions">
            <a-button type="primary" class="actionButton" @click="isModalVisible = true">
              <template #icon>
                <PlusOutlined />
              </template>
              新建课程
            </a-button>
          </a-space>
        </div>
        <div class="controls">
          <a-input-search
            v-model:value="searchValue"
            placeholder="搜索"
            class="search"
            enter-button
            @search="handleSearch"
          />
        </div>
      </div>
      <div class="listContainer">
        <a-list :data-source="courseData">
          <template #renderItem="{ item }">
            <a-list-item :key="item.courseFileId" class="listItem" @click="handleItemClick(item)">
              <div class="listItemContent">
                <div class="courseImage">
                  <img :src="item.courseImageUrl" alt="课程图标" class="icon">
                </div>
                <div class="courseDetails" :style="{ marginLeft: '1.25rem' }">
                  <h3 class="courseName">
                    {{ item.name }}
                  </h3>
                  <div class="courseMeta">
                    <span>更新时间: {{ item.createdAt || '未知时间' }}</span>
                  </div>
                </div>
                <div class="courseActions" :style="{ marginLeft: '-2.5rem' }">
                  <a-button
                    type="primary"
                    @click.stop="handleMove(item)"
                  >
                    <template #icon>
                      <EditOutlined />
                    </template>
                    编辑
                  </a-button>
                  <a-button
                    type="default"
                    class="secondary-btn"
                    @click.stop="handleItemClick(item)"
                  >
                    <template #icon>
                      <FolderOpenOutlined />
                    </template>
                    管理课程资源
                  </a-button>
                  <a-button
                    type="default"
                    @click.stop="copyUrl(item)"
                  >
                    <template #icon>
                      <ExportOutlined />
                    </template>
                    分享
                  </a-button>
                  <a-button
                    type="default"
                    danger
                    @click.stop="showDeleteConfirm(item)"
                  >
                    <template #icon>
                      <DeleteOutlined />
                    </template>
                    删除
                  </a-button>
                </div>
              </div>
            </a-list-item>
          </template>
        </a-list>
      </div>
    </a-spin>

    <!-- 新建课程模态框 -->

    <a-modal
      v-model:open="isModalVisible"
      title="新建课程"
      ok-text="确定"
      cancel-text="取消"
      :width="600"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form layout="vertical">
        <div style="display: flex;">
          <div style="margin-top: 20px;">
            <a-upload
              accept="image/*"
              list-type="picture-card"
              :show-upload-list="true"
              :max-count="1"
              :file-list="courseImage"
              @change="handleCourseImageChange"
            >
              <template v-if="courseImage.length < 1">
                <div style="width: 100px; height: 100px; background-color: #f0f0f0;">
                  <PlusOutlined style="margin-top: 30px;" />
                  <div style="margin-top: 0;">
                    上传图片
                  </div>
                </div>
              </template>
            </a-upload>
          </div>
          <div style="flex: 1; margin-left: 20px;">
            <a-form-item
              label="课程名称"
              name="courseName"
              :rules="[{ required: false, message: '请输入课程名称' }]"
            >
              <a-input v-model:value="courseName" placeholder="请输入课程名称" />
            </a-form-item>
            <a-form-item
              label="课程标签"
              name="tags"
              :rules="[{ required: false, message: '请输入课程标签' }]"
            >
              <a-input v-model:value="courseTags" placeholder="请输入课程标签" />
            </a-form-item>
          </div>
        </div>

        <div v-for="(teacher, index) in teachers" :key="index" style="margin-bottom: 10px;">
          <h3>授课教师</h3>
          <div style="display: flex; justify-content: space-between;">
            <div style="margin-top: 20px;">
              <a-upload
                accept="image/*"
                list-type="picture-card"
                :show-upload-list="false"
                :max-count="1"
                @change="(info:any) => handleTeacherImageChange(index, info)"
              >
                <template v-if="teacher.imagePreview">
                  <img
                    :src="teacher.imagePreview"
                    alt="教师照片"
                    style="width: 100px; height: 100px;"
                  >
                </template>
                <template v-else>
                  <div style="width: 100px; height: 100px; background-color: #f0f0f0;">
                    <PlusOutlined style="margin-top: 30px;" />
                    <div style="margin-top: 0;">
                      上传图片
                    </div>
                  </div>
                </template>
              </a-upload>
            </div>
            <div style="flex: 1; margin-left: 20px;">
              <div style="display: flex;">
                <a-form-item
                  label="姓名"
                  style="flex: 1; margin-right: 10px;"
                >
                  <a-input
                    v-model:value="teacher.name"
                    placeholder="请输入教师姓名"
                  />
                </a-form-item>
                <a-form-item
                  label="学校或机构"
                  style="flex: 1; margin-right: 10px;"
                >
                  <a-input
                    v-model:value="teacher.institution"
                    placeholder="请输入学校或机构"
                  />
                </a-form-item>
              </div>
              <div style="display: flex;">
                <a-form-item
                  label="职务"
                  style="flex: 1; margin-right: 10px;"
                >
                  <a-input
                    v-model:value="teacher.position"
                    placeholder="请输入职务"
                  />
                </a-form-item>
                <a-form-item
                  label="职称"
                  style="flex: 1; margin-right: 10px;"
                >
                  <a-input
                    v-model:value="teacher.title"
                    placeholder="请输入职称"
                  />
                </a-form-item>
              </div>
              <a-button
                type="link"
                danger
                @click="handleRemoveTeacher(index)"
              >
                删除
              </a-button>
            </div>
          </div>
        </div>

        <a-button
          type="dashed"
          style="width: 100%; margin-bottom: 20px;"
          @click="handleAddTeacher"
        >
          <PlusOutlined /> 添加
        </a-button>

        <a-form-item
          name="description"
          label="课程简介"
        >
          <a-textarea v-model:value="courseDescription" placeholder="请输入课程简介" auto-size />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
  <a-modal v-model:open="deleteConfirmVisible" width="550" closable centered>
    <p>您确定要删除所选中的内容吗？内容一旦被删除将不能恢复。</p>
    <template #title>
      <ExclamationCircleOutlined style="color: red;" />
      删除
    </template>

    <template #footer>
      <a-button key="back" class="delete-button" @click="setDeleteConfirmVisible(false)">
        取消
      </a-button>
      <a-button key="submit" type="danger" class="delete-button" style="background-color: #FF7575; border-color: #FF7575; color:#FFFFFF;" @click="handleDelete(deleteItemTmp)">
        确定
      </a-button>
    </template>
  </a-modal>
  <EditCourseModal
    :visible="isVisible"
    :course-id="courseId || 'default_course_id'"
    :fetch-courses="fetchCourses"
    @close="handleNotMove"
  />
</template>

<style scoped lang="scss">
@use '@/style/custom-theme.scss' as *;
.secondary-btn {
  color: $button-secondary-text-color !important;
  background-color: $button-secondary-bg !important;
}
.header-section {
  position: sticky;
    top: 0; /* 距离顶部的位置 */
    z-index: 10; /* 确保在其他内容之上 */
}
.delete-button {
font-size: 1rem;  padding: 0px 1.25rem;
}
.courseManager {
  padding-right: 1.25rem;
  height: calc(100vh - 6.25rem);
  overflow: hidden;

  .title {
    font-size: 1.25rem;
    margin-bottom: 1.25rem;
  }

  .controlc {
    display: flex;
    justify-content: space-between;
    margin-bottom: 1.25rem;

    .actionButton {
      font-size: 1rem;
      margin-right: 2rem;
      padding: 0rem 0.9375rem ;
      padding-top: 0.5rem;
      padding-bottom: 2rem;
    }
  }

  .controls {
    display: flex;
    margin-bottom: 1.25rem;

    .search {
      width: 18.75rem;
    }
  }

  .listContainer {
    flex: 1;
    height: calc(100vh - 6.25rem - 6rem); /* 减去标题和搜索栏的高度 */
    overflow-y: auto; /* 列表部分可滚动 */
    overflow-x: auto;
    white-space: nowrap;
    width: 100%;
    .listItem {
      display: flex;
      padding: 1.25rem;
      border-bottom: 1px solid #e8e8e8;

      .listItemContent {
        display: flex;
        width: 100%;
        flex-shrink: 0; /* 防止压缩 */

        .courseImage {
          min-width: 10rem;
          max-width: 10rem;
          img {
            width: 10rem;
            height: 6rem;
            border-radius: 0.25rem;
          }
        }

        .courseDetails {
          min-width: 59.375rem;
          margin-left: 1.25rem;

          .courseName {
            font-size: 1.25rem;
            font-weight: bold;
            color: #333;
            margin-bottom: 0.625rem;
            margin-top: 0.3125rem;
          }

          .courseMeta {
            margin-top: 38px;
            font-size: 0.875rem;
            color: #999;
            span {
              margin-right: 0.625rem;
            }
          }
        }

        .courseActions {
          display: flex;
          justify-content: flex-end;
          align-items: center;

          button {
            font-size: 16px;
            margin-left: 0.625rem;
          }
        }
      }
    }
  }
}
</style>
